const sm2 = require('sm-crypto').sm2
 
let keypair = sm2.generateKeyPairHex()
 
publicKey = keypair.publicKey // 公钥
privateKey = keypair.privateKey // 私钥
 
function strToHex(str) {
    var hexCharCode = [];
    
    for (var i = 0; i < str.length; i++) {
      hexCharCode.push(str.charCodeAt(i).toString(16));
    }
    // 记住这里的join一定是空，不要误打了空格
    return hexCharCode.join('');
  }
  
privateKey = "f2239272674a62e63ea56b6bca260b2b40bf9d9215e0043ebee092413d77df5c"
publicKey = "04116176183480c574072af57c6b6c87b404dd9a4465ddcadcd75f7bdf87a721e9d95ba62c57ab2ccc842633f4ca34979d787188f0d1b40691edfbc461bb3e7225" 

// me   04f81e1e3a485ab39983a3e4c1916e3384387b6293e9eb395ee4b8b2a05d5414930ad71ae4ada90abaf0aa527ff0c30469e2222628477fab7efbbff27c82393f6f
 
 // you  041dcfc3167804b7a9b2e0908cf687f89d98438e6a8759c4947bfbd04602bcb41541b6a3345c118ef70b399146aa8c4c9f05fe27509f99b3895a7c09af17b15dbd

console.log(publicKey)
console.log(privateKey)

const cipherMode = 1 // 1 - C1C3C2，0 - C1C2C3，默认为1
let msgString = 'zhonghuarenmingongheguowansui'
let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode) // 加密结果

console.log(encryptData)
//encryptData = "0459d70ea62607fa1f4b47d1b952ff6b030e91a18644b9b2573f477614c1808ab1f9b0cbb079bb5cb5af8111a24ee358def126ef978067216187bb22a67bd9981120aa614e6db840225b0f16747f1e25af914f664065a77b9aefce31335f5bf936401604ce7f2f3a273d6153297437f6939b95d3918da1af2c27784331fe"


if(encryptData.startsWith('04'))
{
	encryptData = encryptData.slice(2,encryptData.length)
}
let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode) // 解密结果
console.log('原文:'+decryptData)
 
 let verifyResult = sm2.doSignature(strToHex(msgString),privateKey,{der: true, hash: true})
 console.log(verifyResult)
 //verifyResult = "3046022100d513225c2d37917cc9e1801a79aee6b429971a9e81d7fda5206af25048469aac022100a4de2d5d1b1b1c5d763d386c918907c224f8071a3702b2beadd1d318ea995aea";
 let res = sm2.doVerifySignature(strToHex(msgString),verifyResult,publicKey,{der: true, hash: true})
 console.log("检验结果"+res)
 
 
  verifyResult = sm2.doSignature(msgString,privateKey,{der: true, hash: true})
 console.log(verifyResult)
 verifyResult = "3045022100a268a6e41b3637492c5e3a423d0d7c27f05d81d7c808c47839f540fc64d0e4a4022016cf78b94546bbf56e148b2d827f250ec1bc11d7033fbe0c28b8a3e65cf2091c";
  res = sm2.doVerifySignature(msgString,verifyResult,publicKey,{der: true, hash: true})
 console.log("检验结果"+res)
 
 
 
 